package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserSecretVolume;
import com.yanqu.road.entity.task.TaskConditionInfo;
import com.yanqu.road.entity.task.TaskInfo;
import com.yanqu.road.entity.task.UserTaskData;
import com.yanqu.road.logic.bussiness.player.SecretVolumeBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.server.SecretVolumeProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.mall.MallModule;
import com.yanqu.road.server.gameplayer.module.task.TaskModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.logic.task.BaseTaskData;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.activity.wealthscroll.WealthScrollActivityMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.config.TaskMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.secretVolume.SecretVolumeMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * 密卷
 */
public class SecretVolumeModule extends GeneralModule {

    private static RandomHelper threadSafeRandom = new RandomHelper();

    private UserSecretVolume userSecretVolume;

    public SecretVolumeModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        userSecretVolume = SecretVolumeBussiness.getUserSecretVolume(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public void loginSendMsg() {
        //策划配错了重新登录
        resetSecretVolume();
        syncSecretVolume();
    }

    @Override
    public boolean saveData() {
        if (userSecretVolume != null) {
            if (userSecretVolume.isInsertOption()) {
                SecretVolumeBussiness.addUserSecretVolume(userSecretVolume);
            } else if (userSecretVolume.isUpdateOption()) {
                SecretVolumeBussiness.updateUserSecretVolume(userSecretVolume);
            }
        }
        return true;
    }

    public UserSecretVolume getUserSecretVolume(){
        return userSecretVolume;
    }

    //当前是否正在档期
    public boolean isNowInTime(){
        if(userSecretVolume == null){
            return false;
        }
        //已经过期了且没有下一期了
        if(userSecretVolume.getStartDate() + (long)userSecretVolume.getDateLength() * 24*60*60*1000 < System.currentTimeMillis()){
            return false;
        }
        return true;
    }

    private void syncSecretVolume(){
        SecretVolumeProto.SecretVolumeMsg.Builder msg = SecretVolumeProto.SecretVolumeMsg.newBuilder();
        if(isNowInTime()){
            String bigReward = "";
            try {
                List<String> bigRewardList = StringUtils.stringToStringList(GameConfig.SECRET_VOLUME_SPECIAL_ITEM,"\\|");
                bigReward = bigRewardList.get(userSecretVolume.getNo()-1);
            }catch (Exception $e){
                log.error("配置库SECRET_VOLUME_SPECIAL_ITEM有问题");
            }
            msg.setNo(userSecretVolume.getNo());
            msg.setStartTime((int)(userSecretVolume.getStartDate()/1000));
            msg.setDateLength(userSecretVolume.getDateLength());
            msg.setExp(userSecretVolume.getExp());
            msg.setIntegral(userSecretVolume.getIntegral());
            msg.setIsBuy(userSecretVolume.isBuy());
            msg.setBigReward(bigReward);
        }else{//假如沒有或者沒有開始就返回期数0的
            msg.setNo(0);
            msg.setStartTime(0);
            msg.setDateLength(0);
            msg.setExp(0);
            msg.setIntegral(0);
            msg.setIsBuy(false);
            msg.setBigReward("");
        }
        player.sendPacket(Protocol.U_SECRET_VOLUME_SYNC, msg);
    }

    public void initSystem(){
        resetSecretVolume();
    }

    public void addSecretVolumeExp(long exp){
        if(isNowInTime()){
            userSecretVolume.setExp(exp+userSecretVolume.getExp());
            player.notifyListener(eGamePlayerEventType.SecretVolumeExp.getValue(),exp);
            syncSecretVolume();
        }
    }

    public void addSecretVolumeIntegral(long integral,eLogMoneyType master,eLogMoneyType son){
        if(isNowInTime()){
            long oldIntegral = userSecretVolume.getIntegral();
            userSecretVolume.setIntegral(integral+userSecretVolume.getIntegral());
            player.getModule(AttributeModule.class).addAttribute(ePlayerAttrType.SecretVolumeIntegral,integral);
            syncSecretVolume();
            LogMgr.addLogSecretVolumeIntegral(player.getUserId(), oldIntegral, oldIntegral+integral, integral, master.getValue(), son.getValue());
        }
    }

    public boolean isIntegralEnough(long integral){
        if(integral <= 0){
            return false;
        }
        BigInteger preReduceValue = player.getModule(PreReduceModule.class).getPreReduceItemMap().get(GameConfig.SECRET_VOLUME_INTEGRAL_ID);
        if (null == preReduceValue) {
            preReduceValue = BigInteger.ZERO;
        }
        long temp = preReduceValue.longValue();
        if(userSecretVolume.getIntegral() + temp < integral){
            return false;
        }
        return true;
    }

    public boolean removeIntegral(long integral, eLogMoneyType master,eLogMoneyType son){
        if(integral <= 0){
            return false;
        }
        if(userSecretVolume.getIntegral() < integral){
            return false;
        }
        long oldIntegral = userSecretVolume.getIntegral();
        userSecretVolume.setIntegral(userSecretVolume.getIntegral()-integral);
        syncSecretVolume();
        LogMgr.addLogSecretVolumeIntegral(player.getUserId(), oldIntegral, oldIntegral-integral, -integral, master.getValue(), son.getValue());
        return true;
    }

    public boolean removeIntegralToNegative(long integral, eLogMoneyType master,eLogMoneyType son){
        if(integral <= 0){
            return false;
        }
        long oldIntegral = userSecretVolume.getIntegral();
        userSecretVolume.setIntegral(userSecretVolume.getIntegral()-integral);
        syncSecretVolume();
        LogMgr.addLogSecretVolumeIntegral(player.getUserId(), oldIntegral, oldIntegral-integral, -integral, master.getValue(), son.getValue());
        return true;
    }

    //注意，没有密卷也会被判定为没买
    public boolean isBuySecretVolume(){
        resetSecretVolume();
        if(!isNowInTime()){
            return false;
        }
        return userSecretVolume.isBuy();
    }

    public void buySecretVolume(){
        resetSecretVolume();
        if(isNowInTime()){
            userSecretVolume.setIsBuy(true);
            syncSecretVolume();
            WorldMessageMgr.worldNotify(player, eMessageType.SecretVolume.getValue());
        }
    }

    //上一次的登录时间，用来判断是不是上次已经登录过触发过财神密卷，用于策划空档期没有配置财神密卷，没有登录的玩家平滑连接，登录过的玩家跳跃连接，从配置时候开始算时间
    private long lastLoginTime = 0;

    public void setLastLoginTime(long lastLoginTime){
        this.lastLoginTime = lastLoginTime;
    }

    //判断要不要重置
    public void resetSecretVolume(){
        if(SystemOpenMgr.systemOpen(player, eSystemId.SecretVolume.getValue())) {

            // 重置前先判断自动发奖
            checkAutoSendReward();
            if(null == userSecretVolume){
                //7.4新增 【【V7.4】财神秘卷迭代 - 服务端】 有新的财神密卷 这个过期了就过期了吧
                if (!WealthScrollActivityMgr.isNewWealthScrollOpening()){
                    newUserSecretVolume(1,0);
                }
            }else{
                //必须按照时间接下去接到对应时间的那一期
                /*List<Integer> infoList = SecretVolumeMgr.getUserNowNoDay(userSecretVolume,this.lastLoginTime);
                if(infoList.get(0) != userSecretVolume.getNo()){
                    newUserSecretVolume(infoList.get(0),infoList.get(1));
                }*/
                //这一期已经过去了直接接到下一期
                if(System.currentTimeMillis() > userSecretVolume.getStartDate() + (long)userSecretVolume.getDateLength()*24*60*60*1000){
                    //7.4新增 【【V7.4】财神秘卷迭代 - 服务端】 有新的财神密卷 这个过期了就过期了吧
                    if (!WealthScrollActivityMgr.isNewWealthScrollOpening()){
                        //下一期是第几期 超出配置的最大期数会返回2
                        int newSecretVolumeNo = SecretVolumeMgr.getSecretVolumeNo(userSecretVolume.getNo() + 1);
                        //如果下一期已经重置回第二期了
                        if (newSecretVolumeNo < userSecretVolume.getNo()){
                            //重置补发标识到第一期 这样第二期开始会补发
                            player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.SecretVolumeAutoSendRewardNo, newSecretVolumeNo - 1);
                        }
                        newUserSecretVolume(newSecretVolumeNo);
                    } else {
                        synchronized (this){
                            //如果旧的过期了 要把积分转化成新的道具
                            int scoreItemId = WealthScrollActivityMgr.getScoreItemId();
                            long hasScore = userSecretVolume.getIntegral();
                            if (scoreItemId <= 0){
                                log.error("玩家旧财神密卷更新到新财神密卷时,积分转化失败,玩家id{},数量{}",getUserId(), hasScore);
                            }else {
                                if (hasScore > 0){
                                    userSecretVolume.setIntegral(0);
                                    player.getModule(CurrencyModule.class).addCurrency(new Property(scoreItemId,hasScore),eLogMoneyType.WealthScroll,eLogMoneyType.SecretVolumeToWealthScroll);
                                    log.info("玩家id:{}完成财神密卷新旧过度,补发积分:{}",getUserId(), hasScore);
                                }
                            }
                        }
                    }
                }
                //七日重置任务
                player.getModule(TaskModule.class).resetSecretVolumeSevenDay(false);
            }
            syncSecretVolume();
        }
    }

    //有可能跳关卡,指点开始时间的
    private void newUserSecretVolume(int no,int day){
        //配置没配
        if(SecretVolumeMgr.getNoDate(no) == 0){
            return;
        }
        //必须从第一期开始
        if(userSecretVolume == null && no != 1){
            return;
        }
        UserSecretVolume newOne = new UserSecretVolume();
        newOne.setUserId(getUserId());
        newOne.setNo(no);
        newOne.setGetRewardLevel("");
        newOne.setDateLength(SecretVolumeMgr.getNoDate(no));
        newOne.setIsBuy(false);
        newOne.setExp(0);
        newOne.setUpdateTime(System.currentTimeMillis());
        //第一期从1开始且是当前时间
        if(no == 1){
            newOne.setStartDate(DateHelper.getTodayZeroTimeStamp());
            newOne.setIntegral(0);
        }else {
            newOne.setStartDate(userSecretVolume.getStartDate() + (long)day * 24 * 60 * 60 * 1000);
            //继承上一次的积分数量
            newOne.setIntegral(userSecretVolume.getIntegral());
        }

        userSecretVolume = newOne;
        userSecretVolume.setInsertOption();

        //这边是要强制重置的
        player.getModule(TaskModule.class).resetSecretVolumeSevenDay(true);
        player.getModule(TaskModule.class).resetSecretVolumeLevel(newOne.getStartDate(),newOne.getDateLength());
        //重置密卷商店的商品
        player.getModule(MallModule.class).resetCustomMall(eShopType.SecretVolumeMall.getValue());
    }

    //不指定开始时间的，重置的时候直接开始
    private void newUserSecretVolume(int no){
        //配置没配
        if(SecretVolumeMgr.getNoDate(no) == 0){
            return;
        }
        //必须从第一期开始
        if(userSecretVolume == null && no != 1){
            return;
        }
        UserSecretVolume newOne = new UserSecretVolume();
        newOne.setUserId(getUserId());
        newOne.setNo(no);
        newOne.setGetRewardLevel("");
        newOne.setDateLength(SecretVolumeMgr.getNoDate(no));
        newOne.setIsBuy(false);
        newOne.setExp(0);
        newOne.setUpdateTime(System.currentTimeMillis());
        newOne.setStartDate(DateHelper.getTodayZeroTimeStamp());
        //第一期从1开始且是当前时间
        if(no == 1){
            newOne.setIntegral(0);
        }else {
            //继承上一次的积分数量
            newOne.setIntegral(userSecretVolume.getIntegral());
        }

        userSecretVolume = newOne;
        userSecretVolume.setInsertOption();

        //这边是要强制重置的
        player.getModule(TaskModule.class).resetSecretVolumeSevenDay(true);
        player.getModule(TaskModule.class).resetSecretVolumeLevel(newOne.getStartDate(),newOne.getDateLength());
        //重置密卷商店的商品
        player.getModule(MallModule.class).resetCustomMall(eShopType.SecretVolumeMall.getValue());
    }

    /**
     * 财神秘卷自动发奖（需在重置前调用）
     */
    private void checkAutoSendReward() {

        // 第一次特殊处理
        if (!player.getModule(AttributeModule.class).getUserAttributeMap().containsKey(ePlayerAttrType.SecretVolumeAutoSendRewardNo)) {
            if (userSecretVolume == null) {
                // 未解锁
                player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.SecretVolumeAutoSendRewardNo, 0);
            } else if (System.currentTimeMillis() >= userSecretVolume.getStartDate() + (long) userSecretVolume.getDateLength() * 24 * 60 * 60 * 1000) {
                // 已过期
                player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.SecretVolumeAutoSendRewardNo, userSecretVolume.getNo());
            } else {
                // 其他
                player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.SecretVolumeAutoSendRewardNo, userSecretVolume.getNo() - 1);
            }
        }

        if (userSecretVolume == null) return;

        // 校验是否过期
        if (System.currentTimeMillis() < userSecretVolume.getStartDate() + (long) userSecretVolume.getDateLength() * 24 * 60 * 60 * 1000)
            return;

        // 校验是否发过奖
        long autoRewardNo = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.SecretVolumeAutoSendRewardNo);
        if (userSecretVolume.getNo() <= autoRewardNo) return;

        // 获取未领取奖励
        Property reward = new Property();
        Map<Integer, BaseTaskData> baseTaskDataMap = player.getModule(TaskModule.class).getBaseTaskDataMap();
        for (BaseTaskData baseTaskData : baseTaskDataMap.values()) {
            UserTaskData userTaskData = baseTaskData.getUserTaskData();
            if (userTaskData == null) {
                continue;
            }
            if (userTaskData.getTaskType() == eTaskType.SecretVolumeLevel.getValue()) {
                // 未领奖
                if (userTaskData.getState() == 0) {
                    TaskConditionInfo taskConditionInfo = baseTaskData.getBaseCondition().getTaskConditionInfo();
                    TaskInfo taskInfo = TaskMgr.getTaskInfoById(taskConditionInfo.getTaskId());
                    BigInteger needExp = taskConditionInfo.getParamList().get(3);
                    boolean canComplete = false;
                    if (taskInfo.getLittleType() == 2) { // 付费
                        if (userSecretVolume.getExp() >= needExp.longValue() && userSecretVolume.isBuy()) {
                            canComplete = true;
                        }
                    } else { // 免费
                        if (userSecretVolume.getExp() >= needExp.longValue()) {
                            canComplete = true;
                        }
                    }
                    // 能完成
                    if (canComplete) {
                        userTaskData.setState(1); // 虽然马上要重置了但还是设置下状态比较稳
                        userTaskData.setFinishTime(System.currentTimeMillis() / 1000);
                        reward.addProperty(taskInfo.getSecretVolumeReward(userSecretVolume.getNo()));
                    }
                }
            }
        }

        // 改状态
        player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.SecretVolumeAutoSendRewardNo, userSecretVolume.getNo());

        log.info("财神秘卷过期自动发奖：用户ID={}，期数={}，经验值={}，是否购买={}，奖励={}.",
                player.getUserId(), userSecretVolume.getNo(), userSecretVolume.getExp(), userSecretVolume.isBuy(), PropertyHelper.parsePropertyToString(reward));

        // 发奖
        if (!reward.isNothing()) {
            String mailTitle = MultipleLanguageMgr.getContent(MailManager.SECRET_VOLUME_AUTO_SEND_REWARD_TITLE, player.getLanguage());
            String mailContent = MultipleLanguageMgr.getContent(MailManager.SECRET_VOLUME_AUTO_SEND_REWARD_CONTENT, player.getLanguage());
            MailManager.sendMailOnLoad(player, eMailType.SYSTEM.getValue(), PropertyHelper.parsePropertyToString(reward), mailContent, mailTitle);
        }

    }


}
